<template>
  <div id="app">
    <div class="container">
      <div class="close">
        <span class="iconfont iconicon-test"> </span>
      </div>
      <div class="logo">
        <span class="iconfont iconnew"></span>
      </div>
      <div class="inputs">
        <!-- 双向绑定 v-model
                为子组件的value 赋值
                监听子组件所翻出的input 事件 -->
        <myinput
          v-model="user.username"
          :rules="/^1\d{4}$|^1[35789]\d{9}$/"
          msg="请输入5位或11位手机号"
          placeholder="用户名/手机号"
        ></myinput>
        <myinput
          placeholder="密码"
          class="input"
          type="password"
          :rules="/^.{3,16}$/"
          v-model="user.password"
        />
      </div>
      <p class="tips">没有账号？ <a href="#/register" class="">去注册</a></p>
      <!-- 3 使用封装按钮 -->
      <mybutton @click="login" type="primay">登录</mybutton>
    </div>
  </div>
</template>

<script>
// import { Button } from "vant";
// import "vant/lib/button/style";
// 1 引入按钮的封装
import mybutton from "@/components/mybutton.vue";
import myinput from "@/components/myinput.vue";
import { login } from "@/apis/user.js";
export default {
  components: {
    // 2 注册
    mybutton,
    myinput,
    // 键值对
    // "van-button": Button,
  },
  data() {
    return {
      user: {
        username: "10086",
        password: "123",
      },
    };
  },
  methods: {
    // async 标记当前方法有异步操作
    async login() {
      // 正则判定用户输入的类型
      if (
        /^(\d{5,6})$|^(1\d{10})$/.test(this.user.username) &&
        /^\S{3,16}$/.test(this.user.password)
      ) {
        let res = await login(this.user);
        console.log(res);
        if (res.data.message == "用户不存在") {
          // 如果密码或用户名输入错误就使用提示框提示用户
          this.$toast.fail(res.data.message);
        } else {
          this.$toast.success("登录成功");
          // 将token 储存到本地
          localStorage.setItem("token", res.data.data.token);
          localStorage.setItem("id", JSON.stringify(res.data.data.user));
          // 如果成功就实现页面跳转  路由跳转使用 $router.push  编程式导航
          let url = decodeURIComponent(window.location.hash.split("=")[1]);
          if (url && url != undefined) {
            this.$router.push({ path: url });
          } else {
            this.$router.push({ path: `personal/${res.data.data.user.id}` });
          }
        }
      } else {
        // 如果输入错误的类型就提示用户 使用 框架中的toast提示用户
        this.$toast.fail("用户数据输入不合法");
      }
    },
  },
};
</script>


<style lang="less" scoped>
.container {
  padding: 20px;
}

.close {
  span {
    font-size: 27 / 360 * 100vw;
  }
}

.logo {
  display: flex;
  justify-content: center;

  span {
    display: block;
    font-size: 126 / 360 * 100vw;
    color: #d81e06;
  }
}

.inputs {
  input {
    margin-bottom: 20px;
  }
}

.tips {
  text-align: right;
  margin-bottom: 20px;

  a {
    color: #3385ff;
  }
}
</style>